/**
 * Created by Administrator on 2017/4/13.
 */
angular.module('HTRD_AutoConsole.A')
	.controller('HomeWarnListCtrl', ['$scope', '$state', '$window','HomeServ','DateParseServ','$timeout',function($scope, $state, $window,HomeServ,DateParseServ,$timeout) {
		console.log('HomeWarnListCtrl');

		//面包屑
	    	var breadcrumbsData = [
		      {
		        'iconClass': 'icon-home',
		        'text': '首页',
		        'link': 'console.base.home.index'
		      },
		      {
		        'text': '执行告警'
		      }
	    	];

		var getHomeWarnList;
		var homeWarnListConfig = {
			page: 1,
			limit: 20,
			sort:'-id',
		};

		var statusMap = {
		    1:{
		      className: "default",
		      text:"检测异常"
		    },
		    2:{
		      className: 'timeout',
		      text:"执行超时"
		    },
		    3:{
		      className: 'error',
		      text:"执行错误"
		    }
		  };

		var changeHomeWarnProcessSort = function(){
			$scope.classState = !!!$scope.classState
			if($scope.classState === true){
				$scope.homeWarnListConfig.sort= 'started_at',
				getHomeWarnList($scope.homeWarnListConfig)

			}else{
				$scope.homeWarnListConfig.sort= '-started_at',
				getHomeWarnList($scope.homeWarnListConfig)
			}
		}


		var bindListener = function() {
			$scope.changeHomeWarnProcessSort = changeHomeWarnProcessSort
		};

		var initPlugins = function() {
			$scope.breadcrumbsData = breadcrumbsData;
			//执行(分页)的配置
			$scope.homeWarnListConfig = homeWarnListConfig;
			$scope.classState = false;

			//执行告警
			getHomeWarnList = function (homeWarnListConfig) {
				HomeServ.getWarnRun(homeWarnListConfig)
					.then(function(data) {

						if(data.status === 200){
							$scope.warnRun = data;
							$scope.warnRun.result = $scope.warnRun.results.data;

							$scope.warnRun.result .map(function(item) {
								var model = statusMap[item.level];
								var started_at = DateParseServ.dateParse(item.started_at);
								item.color = model.className;
						            	item.level = model.text;
								item.started_at = started_at;
						          });

							$scope.$broadcast("toList",{
								list: data.results.data,
								count: data.results.count,
								limit: $scope.homeWarnListConfig.limit,
								page: $scope.homeWarnListConfig.page || data.results.page
							})
						}
					});
			};
			$timeout(function () {
				getHomeWarnList()

			},1000);
			$scope.$on('toPage',function (evt,data) {
				$scope.homeWarnListConfig.page = data.page;
				getHomeWarnList($scope.homeWarnListConfig)
			});
		};

		var init = function() {
			bindListener();
			initPlugins()
		};

		init();
	}]);
